package ar.edu.itba.it.pdc.app.config.impl;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

import ar.edu.itba.it.pdc.app.config.ProxySettings;
import ar.edu.itba.it.pdc.app.config.mapping.Settings;
import ar.edu.itba.it.pdc.app.exception.ConfigurationException;

public class ProxySettingsXMLImpl implements ProxySettings {

	private String pathFile;
	private Settings currentSettings;
	private boolean changed = true;
	
	public void setPathFile(String path) {
		this.pathFile = path;
	}

	public Settings loadSettings() {
		if(changed) {
			try {
				JAXBContext jc = JAXBContext.newInstance("ar.edu.itba.it.pdc.app.config.mapping");
				Unmarshaller u = jc.createUnmarshaller();
				JAXBElement<Settings> root = u.unmarshal(new StreamSource(new File(pathFile)), Settings.class);
				this.currentSettings = root.getValue();
				this.changed = false;
			} catch (Exception e) {
				throw new ConfigurationException("There are problems with the config file");
			}
		}
		return currentSettings;
	}

	public synchronized void saveSettings(Settings settings) {
		JAXBContext jc;
		try {
			jc = JAXBContext.newInstance("ar.edu.itba.it.pdc.app.config.mapping");
			Marshaller m = jc.createMarshaller();
			m.marshal(settings, new FileOutputStream(pathFile));
			changed = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new ConfigurationException("There are problems with the config file");
		}
	}

}
